package com.liukai.novel_info.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.liukai.novel_base.base.BaseActivity;
import com.liukai.novel_commons.Result;
import com.liukai.novel_commons.entities.NovelChapter;
import com.liukai.novel_commons.entities.NovelInfo;
import com.liukai.novel_commons.entities.NovelRack;
import com.liukai.novel_commons.utils.Constans;
import com.liukai.novel_commons.utils.FileUtil;
import com.liukai.novel_commons.utils.JSONUtil;
import com.liukai.novel_commons.utils.LightUtils;
import com.liukai.novel_commons.utils.LogUtils;
import com.liukai.novel_info.R;
import com.liukai.novel_info.R2;
import com.liukai.novel_info.adapter.ReadLeftAdapter;
import com.liukai.novel_info.call_back.INovelCallBack;
import com.liukai.novel_info.call_back.INovelRackCallBack;
import com.liukai.novel_info.presenter.impl.NovelPresenterImpl;
import com.liukai.novel_info.presenter.impl.NovelRackPresenterImpl;
import com.liukai.novel_info.view.BookPageBezierHelper;
import com.liukai.novel_info.view.BookPageView;

import java.io.IOException;
import java.util.Date;

import butterknife.BindView;

public class ReadActivity extends BaseActivity implements INovelCallBack, INovelRackCallBack {

    @BindView(R2.id.book_page_view)
    BookPageView mBookPageView;

    @BindView(R2.id.progress)
    TextView progress;

    //    @BindView(R2.id.bottom_navigation)
    BottomNavigationView mBottomNavigationView;

    @BindView(R2.id.chapter_name)
    TextView tvChapterName;

    private String mFilePath;
    private BookPageBezierHelper mHelper;

    //    @BindView(R2.id.setting_view)
//    RelativeLayout mSettingView;
    private int mCurrentLength;
    private PopupWindow mTopWindow;
    private View mTopView;
    private View mBottomView;
    private PopupWindow mBottomWindow;
    private String mNovelId;
    private int mChapterId;
    private NovelPresenterImpl mNovelPresenter;
    private Bitmap mCurrentPageBitmap;
    private NovelRackPresenterImpl mNovelRackPresenter;
    private NovelRack mNovelRack;
    private View mLeftView;
    private PopupWindow mLeftWindow;
    private RecyclerView mLeftRecyclerView;
    private ReadLeftAdapter mReadLeftAdapter;
    private TextView mTvPrePage;
    private TextView mTvNextPage;
    private View mLiangduView;
    private PopupWindow mLiangduWindow;
    private SeekBar mSeekBar;

    private Context mContext;
    private View mBtnBack;
    private ImageView mNovelImg;
    private NovelInfo mNovelInfo;
    private TextView mNovelAuthor;
    private TextView mNovelName;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_read;
    }

    @Override
    protected void initData(Context context) {

        // 注册NovelPresenterImpl
        mNovelPresenter = new NovelPresenterImpl();
        mNovelPresenter.registerCallback(this);
        mNovelRackPresenter = new NovelRackPresenterImpl();
        mNovelRackPresenter.registerCallback(this);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        // 获取上一界面传递的数据
        Intent intent = getIntent();
        if (intent != null) {
            mNovelId = intent.getStringExtra("novelId");
            mFilePath = intent.getStringExtra("filePath");
            mChapterId = intent.getIntExtra("chapterId", 1);
            mNovelRackPresenter.findChapterNameById(mChapterId,mNovelId);
            mNovelPresenter.findNovelById(mNovelId);
        }

        // get size
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;

        // set book helper
        mHelper = new BookPageBezierHelper(width, height);
        mBookPageView.setBookPageBezierHelper(mHelper);

        // currentPage nextPage
        mCurrentPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Bitmap nextPageBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        mBookPageView.setBitmaps(mCurrentPageBitmap, nextPageBitmap);

        openBook(mFilePath, mNovelId, mChapterId);


    }

    @Override
    protected void initView() {

        initReadTopView();
        initReadBottomView();
        initReadLeftView();
        initLiangDuView();

    }

    /**
     * 加载阅读界面头部布局
     */
    private void initReadTopView() {

        mTopView = LayoutInflater.from(ReadActivity.this).inflate(
                R.layout.dialog_read_top, null);
        mTopWindow = new PopupWindow(mTopView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mTopWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        mTopWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        mTopWindow.setOutsideTouchable(true);
        //设置可以点击
        mTopWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
//        mTopWindow.setAnimationStyle(R.style.top_window_anim_style);

        mBtnBack = mTopView.findViewById(R.id.tv_back);

    }

    /**
     * 加载阅读界面底部布局
     */
    private void initReadBottomView() {
        mBottomView = LayoutInflater.from(ReadActivity.this).inflate(
                R.layout.dialog_read_bottom, null);
        mBottomWindow = new PopupWindow(mBottomView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mBottomWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        mBottomWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        mBottomWindow.setOutsideTouchable(true);
        //设置可以点击
        mBottomWindow.setTouchable(true);
        mBottomNavigationView = mBottomView.findViewById(R.id.bottom_navigation);
        mTvPrePage = mBottomView.findViewById(R.id.prePage);
        mTvNextPage = mBottomView.findViewById(R.id.nextPage);

        //进入退出的动画，指定刚才定义的style
//        mBottomWindow.setAnimationStyle(R.style.bottom_window_anim_style);
    }

    /**
     * 加载阅读界面头部布局
     */
    private void initReadLeftView() {

        mLeftView = LayoutInflater.from(ReadActivity.this).inflate(
                R.layout.dialog_read_left, null);
        mLeftWindow = new PopupWindow(mLeftView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mLeftWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        mLeftWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        mLeftWindow.setOutsideTouchable(true);
        //设置可以点击
        mLeftWindow.setTouchable(true);
        //进入退出的动画，指定刚才定义的style
//        mTopWindow.setAnimationStyle(R.style.top_window_anim_style);

        mLeftRecyclerView = mLeftView.findViewById(R.id.recyclerView);
        mNovelImg = mLeftView.findViewById(R.id.novel_img);
        mNovelName = mLeftView.findViewById(R.id.novel_name);
        mNovelAuthor = mLeftView.findViewById(R.id.novel_author);
        mReadLeftAdapter = new ReadLeftAdapter(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mLeftRecyclerView.setLayoutManager(linearLayoutManager);
        mLeftRecyclerView.setAdapter(mReadLeftAdapter);

    }


    /**
     * 加载阅读界面头部布局
     */
    private void initLiangDuView() {

        mLiangduView = LayoutInflater.from(ReadActivity.this).inflate(
                R.layout.dialog_liangdu, null);
        mLiangduWindow = new PopupWindow(mLiangduView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mLiangduWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        mLiangduWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        mLiangduWindow.setOutsideTouchable(true);
        //设置可以点击
        mLiangduWindow.setTouchable(true);
        mSeekBar = mLiangduView.findViewById(R.id.liangdu_seekbar);
//        mSeekBar.setProgress((int)mBrightness);

        LightUtils.with(this);

    }

    @Override
    protected void initListener() {

        // 进度条
        mHelper.setOnProgressChangedListener(new BookPageBezierHelper.OnProgressChangedListener() {
            @Override
            public void setProgress(int currentLength, int totalLength) {
                mCurrentLength = currentLength;
                float progress0 = (float) mCurrentLength * 100 / (float) totalLength;
                String p = String.format("%.2f%%", progress0);
                LogUtils.e(getClass(), "p==========>" + p);
                LogUtils.e(getClass(), "progress0==========>" + progress0);
                progress.setText(p);
            }
        });

        // 点击屏幕中部
        mBookPageView.setOnUserNeedSettingListener(new BookPageView.OnUserNeedSettingListener() {
            @Override
            public void onUserNeedSetting() {
                mTopWindow.showAtLocation(mTopView, Gravity.TOP, 0, 0);
                mBottomWindow.showAtLocation(mBottomView, Gravity.BOTTOM, 0, 0);
                mTopWindow.setClippingEnabled(false);
            }
        });

        // 点击屏幕中部
        mBottomView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height1 = mBottomView.findViewById(R.id.read_bottom_view).getTop();
                int height2 = mTopView.findViewById(R.id.read_top_view).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height1 && y > height2) {
                        closeWindow();
                    }
                }
                return true;
            }
        });

        // 点击屏幕中部
        mTopView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height1 = mBottomView.findViewById(R.id.read_bottom_view).getTop();
                int height2 = mTopView.findViewById(R.id.read_top_view).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height1 && y > height2) {
                        closeWindow();
                    }
                }
                return true;
            }
        });

        // 点击屏幕中部
        mLiangduView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int height1 = mBottomView.findViewById(R.id.read_bottom_view).getTop();
                int height2 = mTopView.findViewById(R.id.read_top_view).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height1 && y > height2) {
                        closeWindow();
                    }
                }
                return true;
            }
        });

        // 第一页和最后一页监听，用于加载上一章或者下一章
        mBookPageView.setOnLastOrFirstPageListener(new BookPageView.OnLastOrFirstPageListener() {
            @Override
            public void onLastOrFirstPage(boolean isLastPage, String novelId, Integer chapterId) {
                if (isLastPage) {
                    // TODO 加载下一章
                    Toast.makeText(ReadActivity.this, "已经是最后一页", Toast.LENGTH_SHORT).show();
                    loadNextPage(novelId, chapterId);
                } else {
                    // TODO 加载上一章
                    Toast.makeText(ReadActivity.this, "已经是第一页", Toast.LENGTH_SHORT).show();
                    loadPrePage(novelId, chapterId);
                }
            }
        });

        mBottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                int itemId = menuItem.getItemId();


                if (itemId == R.id.mulu) {
                    Toast.makeText(ReadActivity.this, "目录", Toast.LENGTH_SHORT).show();
                    openLeftView();
                } else if (itemId == R.id.yejian) {
                    Toast.makeText(ReadActivity.this, "夜间", Toast.LENGTH_SHORT).show();
                } else if (itemId == R.id.liangdu) {
                    closeWindow();
                    Toast.makeText(ReadActivity.this, "亮度", Toast.LENGTH_SHORT).show();
                    mLiangduWindow.showAtLocation(mLiangduView, Gravity.BOTTOM, 0, 0);
                } else {
                    Toast.makeText(ReadActivity.this, "设置", Toast.LENGTH_SHORT).show();
                }

                return true;
            }
        });

        // 点击目录的每一章节
        mReadLeftAdapter.setOnChapterListener(new ReadLeftAdapter.OnChapterListener() {
            @Override
            public void onChapterClick(NovelChapter novelChapter) {
                loadOtherPage(novelChapter.getNovelId(),novelChapter.getChapterId());
                mLeftWindow.dismiss();
            }
        });

        // 点击下一章
        mTvPrePage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadPrePage(mNovelId,mChapterId);
            }
        });

        // 点击上一章
        mTvNextPage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadNextPage(mNovelId,mChapterId);
            }
        });

        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                float num = (float) seekBar.getProgress() / 100;

                //取得屏幕的属性
                WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
                //设置屏幕的亮度
                layoutParams.screenBrightness = num;
                //重新设置窗口的属性
                getWindow().setAttributes(layoutParams);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        mBtnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ReadActivity.this.finish();
            }
        });


    }

    private void closeWindow(){
        mBottomWindow.dismiss();
        mTopWindow.dismiss();
        mLeftWindow.dismiss();
        mLiangduWindow.dismiss();
    }

    /**
     * 打开目录
     */
    private void openLeftView() {
        mLeftWindow.showAtLocation(mLeftView, Gravity.LEFT, 0, 0);
        LogUtils.e(getClass(),mNovelInfo.getNovelImg());
        LogUtils.e(getClass(),mNovelImg.toString());
        Glide.with(this).
                load(Constans.IMAGE_BASE_URL + mNovelInfo.getNovelImg())
                .into(mNovelImg);
        mNovelName.setText(mNovelInfo.getNovelName());
        mNovelAuthor.setText(mNovelInfo.getNovelAuthor());
        mTopWindow.dismiss();
        mBottomWindow.dismiss();
    }

    @Override
    protected void release() {
        super.release();
        mNovelPresenter.unRegisterCallback(this);
        ReadActivity.this.finish();
    }

    /**
     * 打开小说
     */
    private void openBook(String filePath, String novelId, Integer chapterId) {
        mNovelRack = new NovelRack();
        mNovelRack.setUserId(Constans.getUserInfo().getUserId())
                .setNovelId(novelId)
                .setRecentlyChapter(chapterId);
        // 判断路径是否为空
        if (!TextUtils.isEmpty(filePath)) {
            try {
                mHelper.openBook(filePath, novelId, chapterId);
                mHelper.draw(new Canvas(mCurrentPageBitmap));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void loadOtherPage(String novelId,Integer chapterId){
        String filePath = Constans.FILE_PATH + novelId + "-" + chapterId + ".txt";
        if (FileUtil.fileIsExists(filePath)) {
            startNewChapter(filePath, novelId, chapterId);
        } else {
            mNovelPresenter.findNovelChapterById(novelId, chapterId);
        }
    }

    /**
     * 加载上一章
     *
     * @param novelId
     * @param chapterId
     */
    private void loadPrePage(String novelId, Integer chapterId) {
        if (chapterId <= 1)
            return;
        chapterId--;
        String filePath = Constans.FILE_PATH + novelId + "-" + chapterId + ".txt";

        if (FileUtil.fileIsExists(filePath)) {
            startNewChapter(filePath, novelId, chapterId);
        } else {
            mNovelPresenter.findNovelChapterById(novelId, chapterId);
        }

    }

    /**
     * 加载下一章
     *
     * @param novelId
     * @param chapterId
     */
    private void loadNextPage(String novelId, Integer chapterId) {
        chapterId++;
        String filePath = Constans.FILE_PATH + novelId + "-" + chapterId + ".txt";

        if (FileUtil.fileIsExists(filePath)) {
            startNewChapter(filePath, novelId, chapterId);
        } else {
            mNovelPresenter.findNovelChapterById(novelId, chapterId);
        }

    }

    private void startNewChapter(String filePath, String novelId, Integer chapterId) {
        mNovelRack.setRecentlyChapter(chapterId);
        Intent intent = new Intent(ReadActivity.this, ReadActivity.class);
        intent.putExtra("novelId", novelId);
        intent.putExtra("chapterId", chapterId);
        intent.putExtra("filePath", filePath);
        startActivity(intent);
//        startActivityForResult(intent,Constans.CODE_REQUEST_NovelRackFragment);
        ReadActivity.this.finish();
    }

    @Override
    public void findNovelByIdResult(Result result) {
        if (result.getCode() != 200) return;
        mNovelInfo = JSONUtil.resolverResult(result, NovelInfo.class);

    }

    @Override
    public void findNovelChapterByIdResult(Result result) {
        NovelChapter novelChapter = JSONUtil.resolverResult(result, NovelChapter.class);
        String filePath = Constans.FILE_PATH + novelChapter.getNovelId() + "-" + novelChapter.getChapterId() + ".txt";
        String filePath1 = FileUtil.stringToFile(filePath, novelChapter);
        startNewChapter(filePath1, novelChapter.getNovelId(), novelChapter.getChapterId());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        mNovelRackPresenter.updateRackById(mNovelRack);
        ReadActivity.this.finish();
    }

    @Override
    public void updateRackByIdResult(Result result) {

    }

    /**
     * 返回服务器根据小说id和章节id获得的章节名称
     * @param result
     */
    @Override
    public void findChapterNameByIdResult(Result result) {
        String chapterName = (String)result.getData();
        tvChapterName.setText(chapterName);
    }

    @Override
    public void addRackResult(Result result) {

    }

    @Override
    public void loadMuLuResult(Result result) {

    }


}

